package com.cskaoyan.controller;


import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import com.cskaoyan.bean.BaseRespVo;
import com.cskaoyan.bean.UserInfoBean;
import com.cskaoyan.bean.WechatRespData;
import com.cskaoyan.bean.WxLoginReqInfo;
import com.cskaoyan.token.WechatToken;
import me.chanjar.weixin.common.error.WxErrorException;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("wx/auth")
public class WxAuthController {
    @Autowired
    WxMaService wxMaService;

    @RequestMapping("login_by_weixin")
    public BaseRespVo login(@RequestBody WxLoginReqInfo info) throws WxErrorException {
        String code = info.getCode();
        UserInfoBean userInfo = info.getUserInfo();
        if (code == null || userInfo == null) {
            return BaseRespVo.fail();
        }
        WxMaJscode2SessionResult sessionInfo = wxMaService.getUserService().getSessionInfo(code);
        String openid = sessionInfo.getOpenid();
        Subject subject = SecurityUtils.getSubject();
        subject.login(new WechatToken(userInfo,openid));
        WechatRespData wechatRespData = new WechatRespData();
        wechatRespData.setToken((String) subject.getSession().getId());
        wechatRespData.setUserInfo(userInfo);
        return BaseRespVo.ok(wechatRespData);
    }
}
